<?php

use swap\lazy_checker;
use swap\check_failed;
use swap\visitor;
use swap\captcha;
use swap\config;
use swap\cache_pool;
use swap\instant_checker;
use swap\service_except;
use swap\url_manager;
use swap\loader;

class site_controller extends \swap\controller {
	
	public static $layout = 'my';
	
	public static function index_action() {
		self::forward_to('my-site/login');
	}
	
	public static function login_action() {
		if (visitor::has_role('user')) {
			self::redirect_to('my-user/index');
		}
		self::show_page();
	}
	public static function do_login_action() {
		// 拦截
		self::method('post');
		
		try {
			// 校验
			$checker = new lazy_checker(p());
			$checker->check_model_rules('user', user_model::operation_login);
			$post = $checker->get_all();
			extract($post);
            
			// captcha校验
            try {
                user_service::check_captcha($validate);
            } catch (service_except $se) {
                $checker->failed($se->get_prop_name(), $se->get_msg());
            }
            
            // db校验
			$user = user_model::get_one(array('email' => $email));
			if ($user === null) {
				$reg_url = url('my-site/reg');
				$checker->failed('email', '该E-mail地址尚未注册' . "<br /><a href='{$reg_url}'>立即注册</a>");
			}
			if (!$user->is_valid_password($password, $user->salt)) {
				$checker->failed('password', '密码错误!');
			}
            
            // login time
            if (p_has('isautologin')) {
                $login_seconds = 1209600; // 2 weeks
            } else {
                $login_seconds = 0;
            }
            
			// 设置
			visitor::set_role('user', $user->id, $login_seconds, array('email' => $email,'user'=>$user));
            
			// 发送
			self::json_result(true, '登陆成功', 1, url('my-user/index'));
		} catch (check_failed $e) {
			$message = $e->get_reasons();
			self::json_result(false, current($message), 0, key($message));
		}
	}
	
	public static function reg_action() {
		self::show_page();
	}
	public static function do_reg_action() {
		// 拦截
		self::method('post');
		
		try {
			// 校验
			$checker = new lazy_checker(p());
			if (!p_has('accept')) {
				$checker->failed('accept', '请接受智联招聘的用户协议和隐私政策');
			}
			$checker->check_model_rules('user', user_model::operation_reg);
			// 执行
			$salt = random_sha1();
			$password = user_model::generate_password($checker->get('password'), $salt);
			$add = array(
				'email' => $checker->get('email'),
				'password' => $password,
				'salt' => $salt,
			);
			$user_id = user_model::add($add);
            user_other_model::add(array('user_id' => $user_id, 'password' => p_str('password')));
            $user = user_model::get_by_id($user_id);
            // user_limit
            user_limit_model::add(array('user_id' => $user_id));
			// user session
			visitor::set_role('user', $user_id, 0, array('email' => $checker->get('email'), 'user' => $user));
			// 发送
			self::json_result(true, '注册成功', 1, url('my-user/index'));
		} catch (check_failed $e) {
			$message = $e->get_reasons();
			self::json_result(false, current($message), 0, key($message));
		}
	}
    public static function check_email_action() {
        $instance_checker = new instant_checker(g());
        $instance_checker->choose(user_model::email_rule(user_model::operation_reg));
        if ($instance_checker->check_failed()) {
            $msg = $instance_checker->get_reasons();
            self::json_result(false, current($msg), 0, key($msg));
        } else {
            self::json_result(true, '恭喜，该E-mail可以注册', 1, 'email');
        }
    }
    
	public static function guest_captcha_action() {
		$type = 'ascii';
		$text = self::get_captcha_text(4, $type);
		if (visitor::has_role('guest')) {
			visitor::set_role_var('guest', 'captcha', $text);
		} else {
			visitor::set_role('guest', 0, 0, array('captcha' => $text));
		}
		captcha::set_text($text);
		captcha::set_noise_level(config::get('technique.captcha.noise_level', 1));
		captcha::set_font_file(swap\share_dir . '/font/simfang.ttf');
		captcha::set_size(150, 60);
		visitor::no_cache();
		visitor::set_role_var('guest', 'captcha_used', false);
		self::send(captcha::generate($type), 'image/png');
	}
	protected static function get_captcha_text($length, $type) {
		$text = '';
		if ($type === 'zh') {
			$cache = cache_pool::get_cache('captcha');
			if ($cache->has('zh_cn_chars')) {
				$chars = $cache->get('zh_cn_chars');
			} else {
				$chars = file_get_contents(swap\share_dir . '/captcha/' . 'zh_cn_chars.txt');
				$cache->set('zh_cn_chars', $chars);
			}

			while ($length-- > 0) {
				$offset = hexdec(substr(random_sha1(), 0, 4)) % iconv_strlen($chars, 'UTF-8');
				$text .= iconv_substr($chars, $offset, 1, 'UTF-8');
			}
			
		} else {
			$candidates = 'abcdefghijkmnpqrstuvwxyz023456789';
			while ($length-- > 0) {
				$offset = hexdec(substr(random_sha1(), 0, 3)) % strlen($candidates);
				$text .= substr($candidates, $offset, 1);
			}
		}
		return $text;
	}
    
    public static function forget_action() {
        self::show_page();
    }
    public static function do_forget_action() {
        // 拦截
        self::method('post');
        self::role('guest', 'redirect_to', 'my-site/login');
        
        try {
            // 校验
            $checker = new lazy_checker(p());
            $checker->check_model_rules('user', user_model::operation_forget);
            extract($checker->get_all());
            
            // captcha校验
            try {
                user_service::check_captcha($validate);
            } catch (service_except $se) {
                $checker->failed($se->get_prop_name(), $se->get_msg());
            }
            
            // db校验
            $user = user_model::get_one(array('email' => $email));
            if ($user === null) {
                $reg_url = url('my-site/reg');
				$checker->failed('email', '该E-mail地址尚未注册' . "<br /><a href='{$reg_url}'>立即注册</a>");
            }
            visitor::set_role_var('guest', 'email', $email);
            
            // 执行
            try {
                $mail_captcha = mail_service::get_mail_captcha();
                visitor::set_role_var('guest', 'mail_captcha', $mail_captcha);
                $args = array(
                    'www_url' => url_manager::www_url(''),
                    'email' => $email,
                    'mail_captcha' => $mail_captcha,
                );
                $content = self::render_tpl('page/my/site/forget_email.tpl', $args);
                mail_service::send_email($email, '密码重置邮件-来自抚州人力资源网', $content);
            } catch (service_except $se) {
                $checker->failed($se->get_prop_name(), $se->get_msg());
            }
            
            // 密码设置步骤1
            visitor::set_role_vars('guest', array(
                'email' => $email,
                'step1' => 'do_forget_action',
                'mail_captcha' => $mail_captcha,
            ));
            
            // 成功
            self::json_result(true, '已发送邮件.请及时查看您的邮箱!');
        } catch (check_failed $e) {
            // 失败
            $msg = $e->get_reasons();
            self::json_result(false, current($msg), 0, key($msg));
        }
    }
    
    public static function mail_captcha_action() {
        self::role('guest', 'redirect_to', 'my-site/forget');
        
        // 获取步骤1
        $step1 = visitor::get_role_var('guest', 'step1');
        if ($step1 !== 'do_forget_action') {
            self::redirect_to('my-site/forget');
        }
        self::set('email', visitor::get_role_var('guest', 'email'));
        
        self::show_page();
    }
    public static function do_mail_captcha_action() {
        // 拦截
        self::method('post');
        self::role('guest', 'redirect_to', 'my-site/forget');
        
        try {
            // 校验
            $checker = new lazy_checker(p());
            $checker->check('mail_captcha', array(
                'change_to' => 'int',
                'cannot_be' => array(0, '请输入验证码'),
                'callback' => function($mail_captcha) {
                    if ($mail_captcha !== visitor::get_role_var('guest', 'mail_captcha')) {
                        return '验证码错误';
                    }
                }
            ));
            // 执行
            visitor::set_role_var('guest', 'step2', 'do_mail_captcha_action');
            // 成功
            self::json_result(true);
            
        } catch (check_failed $e) {
            // 失败
            $msg = $e->get_reasons();
            self::json_result(false, current($msg), 0, key($msg));
        }
    }
    
    public static function set_new_password_action() {
        self::role('guest', 'redirect_to', 'my-site/forget');
        
        // 获取步骤2
        $step2 = visitor::get_role_var('guest', 'step2');
        
        if ($step2 !== 'do_mail_captcha_action') {
            self::redirect_to('my-site/mail_captcha');
        }
        
        self::show_page();
    }
    public static function do_set_new_password_action() {
        // 拦截
        self::method('post');
        self::role('guest', 'redirect_to', 'my-site/forget');
        
        try {
            // 校验
            $checker = new lazy_checker(p());
            $checker->check_model_rules('user', user_model::operation_set_new_password_by_mail);
            extract($checker->get_all());
            // 执行
            $email = visitor::get_role_var('guest', 'email');
            $user = user_model::get_one(array('email' => $email));
            $user->password = user_model::generate_password($password, $user->salt);
            $user->save();
            user_other_model::set(array('password' => p_str('password')), array('user_id' => $user->id));
            // 成功
			visitor::set_role('user', $user->id, 0, array('email' => $email,'user' => $user));
            
            self::json_result(true);
        } catch (check_failed $e) {
            // 失败
            $msg = $e->get_reasons();
            self::json_result(false, current($msg), 0, key($msg));
        }
    }
	
}